package com.tjsinfo.tjsoa.fileDocument.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.cnblogs.zxub.upload.HttpFileUpload;
import com.cnblogs.zxub.upload.HttpFileUpload.InvalidFileUploadException;
import com.tjsinfo.tjsoa.fileDocument.bo.IFileDocumentFileBo;
import com.tjsinfo.tjsoa.fileDocument.bo.IFileDocumentGroupBo;
import com.tjsinfo.tjsoa.fileDocument.vo.FileDocumentFile;
import com.tjsinfo.tjsoa.system.bo.ISystemUserBo;
import com.tjsinfo.tjsoa.system.vo.TSystemUser;
import com.tjsinfo.tjsoa.system.vo.User;

public class UpLoadAction extends Action {
	private IFileDocumentGroupBo documentGroupBo;
	private ISystemUserBo tjsUserBo;
	private IFileDocumentFileBo documentFileBo;

	public void setTjsUserBo(ISystemUserBo tjsUserBo) {
		this.tjsUserBo = tjsUserBo;
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String returnUrl = "ok";
		String returnString = "";
		DiskFileItemFactory factory = new DiskFileItemFactory();

		factory.setSizeThreshold(1024 * 1024);
		
		ResourceBundle bundle = ResourceBundle.getBundle("com.tjsinfo.tjsoa.fileDocument.properties.systemResource_zh_CN");
		String linshiFile = bundle.getString("linshiFile");
		String path = bundle.getString("fileupload");
		Integer maxSize = Integer.valueOf(bundle.getString("expressFileSize"));
		factory.setRepository(new File(linshiFile));
		HttpFileUpload fu = new HttpFileUpload(factory);
		
		fu.setSizeMax(1024 * 1024 * 1024);
		FileDocumentFile documentFile = null;
		ArrayList listFileName = new ArrayList();
		ArrayList listfileUser = new ArrayList();
		try {
			List fileItemList = fu.parseRequest(request);
			Iterator fileItemListIte = fileItemList.iterator();
			int filesize = 0;
			FileDocumentFile dfile = null;
			while (fileItemListIte.hasNext()) {
				FileItem file = (FileItem) fileItemListIte.next();
				if (!file.isFormField() && !"".equals(file.getName())) {
					filesize += file.getSize();
					listFileName.add(file.getName());
					dfile = documentFileBo.findByFileName(file.getName().substring(file.getName().lastIndexOf("\\")+1, file.getName().length()));
				}
			}
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			
			if (filesize > maxSize*1024*1024) {
				returnString = "一次传送文件的最大容量为" + maxSize + "M,本次传输文件过大！";
				returnUrl = "error";
			}else if(dfile!=null){
				returnString = "您所发布文档与<"+dfile.getFileDocumentGroup().getGroupName()+">种类下的<"+dfile.getFileName()+">相冲突，请修改文档名称重新发布！";
				returnUrl = "error";
			}else {
				String subject = "";
				String keyword = "";
				String beizhu = "";
				String groupid = "";

				if (fileItemList != null) {
					FileItem file = (FileItem) fileItemList.get(fileItemList
							.size() - 1);
					if (file.isFormField() || "".equals(file.getName())) {
						subject = request.getParameter("subject");
						subject = new String(subject.getBytes("ISO-8859-1"), "UTF-8"); 
						groupid = new String(request.getParameter("groupid")
								.getBytes("ISO-8859-1"), "UTF-8");
						if (request.getParameter("keyword") != null
								&& !"".equals(request.getParameter("keyword"))) {
							new String(request.getParameter("keyword")
									.getBytes("ISO-8859-1"), "UTF-8");
						}
						if (request.getParameter("beizhu") != null
								&& !"".equals(request.getParameter("beizhu"))) {
							beizhu = request.getParameter("beizhu");
							if (beizhu != null && !"".equals(beizhu)) {
								beizhu = beizhu.replace("\r\n","<br/>");
								beizhu = beizhu.replace("\"", "“");
							}
						}
						int j = 0;
								String filename = "";
								if (j == 0) {
									fileItemListIte = fileItemList.iterator();
									while (fileItemListIte.hasNext()) {
										FileItem file1 = (FileItem) fileItemListIte.next();
										if (!file1.isFormField()
												&& !"".equals(file1.getName())) {
											String name = file1.getName();
											if(name.indexOf("\\")!=-1){
												int a = name.lastIndexOf("\\");
												name = name.substring(a+1, name
														.length());
											}
											Date date = new Date();
											TSystemUser faUser = tjsUserBo
													.findByIdSystemUser(user
															.getUser_id());
											FileDocumentFile documentFile1 = new FileDocumentFile();
											documentFile1.setTjsUser(faUser);
											while (name.indexOf("  ")!=-1) {
												name = name.replace("  ", " ");
											}
											documentFile1.setFileName(name);
											filename = name;
											documentFile1.setSubject(subject);
											documentFile1.setKeyword(keyword);
											documentFile1.setDocket(beizhu);
											documentFile1.setDatetime(date);
											documentFile1
											.setFileSize(Integer
													.valueOf(String
															.valueOf(file1
																	.getSize())));
											documentFile1.setFilePath(file1
													.getName());
											documentFile1.setState(Integer
													.valueOf(1));
											documentFile1.setFileDocumentGroup(documentGroupBo.findById(groupid));;
											
											documentFileBo.save(documentFile1);
											documentFile = documentFile1;
											file1.write(new File(path+"\\"+filename));
										}
									}
								}
								j++;
					}
						}
				
					}
		}catch (InvalidFileUploadException e) {
			returnString = "本次传输文件过大，如果想提升您的传输容量，请与管理员进行联系！";
			if (e instanceof HttpFileUpload.InvalidFileUploadException) {
				Iterator unAllowFileS = ((HttpFileUpload.InvalidFileUploadException) e)
						.getInvalidFileList().iterator();
				while (unAllowFileS.hasNext()) {
					returnString += "以下文件不被允许" + (String) unAllowFileS.next();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnUrl = "error";
			returnString = "请检查发送文件是否过大及发送人数是否过多！";
			if (e instanceof HttpFileUpload.InvalidFileUploadException) {
				Iterator unAllowFileS = ((HttpFileUpload.InvalidFileUploadException) e)
						.getInvalidFileList().iterator();
				while (unAllowFileS.hasNext()) {
					returnString += "以下文件不被允许" + (String) unAllowFileS.next();
				}
			}
		} finally {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			fu.dispose();
		}
		if (!returnUrl.equals("error") && documentFile!=null) {
			documentFileBo.updateState(documentFile.getFileName());
		}
		request.setAttribute("returnString", returnString);
		request.setAttribute("listFileName", listFileName);
		return mapping.findForward("ok");
	}

	public IFileDocumentFileBo getDocumentFileBo() {
		return documentFileBo;
	}

	public void setDocumentFileBo(IFileDocumentFileBo documentFileBo) {
		this.documentFileBo = documentFileBo;
	}

	public IFileDocumentGroupBo getDocumentGroupBo() {
		return documentGroupBo;
	}

	public void setDocumentGroupBo(IFileDocumentGroupBo documentGroupBo) {
		this.documentGroupBo = documentGroupBo;
	}
}
